/**
 * @description  地图业务方法调用
 * @author 阳坤（1194636148@qq.com）
 * @date   时间：2022/5/25
 */

import store from '@/store'
import { computed } from 'vue'
import { filterPointData } from 'microvideo-map/lib/public-function'
import baseServiceApi from 'bComponent/api/base-service.js'
import eventApi from '../../../api/event.js'
import trafficApi from 'bComponent/api/traffic'
import { lineColors } from '../../../config/traffic'
import { get } from '@/utils'
import temporaryFile from './temporary-file.js'
import { areaConfig } from '@/config/city-config.js'

const roadType = computed(() => store.state.config.roadType)
const areaCode = computed(() => store.state.config.areaCode)
const isProvince = computed(() => store.state.config.isProvince)
const orgId = computed(() => (store.state.user.userInfo.orgInfos ? store.state.user.userInfo.orgInfos[0].orgId : ''))
const showJJJ = store.state.config.pageConfig.pageId == 'jjj'
let cityAreaCode = null

// 基础路线 （路况）
let baseLineData = null
/**
 * 获取基础路线
 * @returns baseLineData
 */
const getBaseLine = () => {
  return new Promise((resolve, reject) => {
    if (baseLineData) {
      // 本地已获取json数据
      resolve(baseLineData)
      return
    }
    baseLineData = {
      gs: [],
      gl: []
    }

    // const cityName = areaConfig.find(i => i.key == cityAreaCode)['cityName']
    let promiseAll = []
    // 2公路路线 1高速路线 空全部
    if (roadType.value == 2) promiseAll = [getGlLxJson(cityAreaCode)]
    else if (roadType.value == 1) promiseAll = [Promise.resolve, baseServiceApi.getGsLxJson()]
    else promiseAll = [getGlLxJson(cityAreaCode), baseServiceApi.getGsLxJson()]

    Promise.allSettled(promiseAll).then(results => {
      console.log('results', results)
      results.forEach((result, index) => {
        // 如果该请求成功

        if (result.status == 'fulfilled' && result.value) {
          // 第一个请求   公路路线
          if (index == 0 && result.value.length) {
            result.value.forEach(item => {
              const data = {
                id: item.properties.id,
                name: item.properties.lxbm + item.properties.lxmc,
                path: item.geometry.coordinates[0],
                config: {
                  lineColor: 'green',
                  selectColor: 'green',
                  lineWidth: 2,
                  selectWidth: 4
                },
                roadName: item.properties.lxbm
              }

              // 省级、空看全部 ， 县站看市级
              if (
                cityAreaCode == 320000 ||
                !cityAreaCode ||
                item.properties.bz == cityAreaCode ||
                item.properties.bz.slice(0, 4) === String(cityAreaCode).slice(0, 4)
              ) {
                baseLineData.gl.push(data)
              }
            })
          } else if (index == 1 && result.value && result.value.length) {
            // 第二个请求  高速路线
            result.value.forEach(item => {
              item.geometry.coordinates.forEach((val, index) => {
                baseLineData.gs.push({
                  id: item.properties.id,
                  name: item.properties.roadCode || item.properties.luxbm + item.properties.luxmc,
                  path: val,
                  config: {
                    lineColor: 'green',
                    selectColor: 'green',
                    lineWidth: 2,
                    selectWidth: 4
                  },
                  roadName: item.properties.roadCode || item.properties.luxbm
                })
              })
            })
          }
          resolve(baseLineData)
        } else if (result.status == 'rejected') {
          reject(result.reason)
        }
      })
    })
  })
}

/**
 * 获取公路基础路线
 * @returns baseLineData
 */
const getGlLxJson = cityAreaCode => {
  return new Promise((resolve, reject) => {
    if (cityAreaCode == '320000') {
      // 获取省级全部路线
      const requestArr = []

      areaConfig.forEach((item, index) => {
        if (item.key == '320000' || !item.key) return
        requestArr.push(baseServiceApi.getGlLxJson(item.key))
      })
      Promise.all(requestArr).then(results => {
        resolve(results.flat())
      })
    } else {
      // 获取单个市级路线
      resolve(baseServiceApi.getGlLxJson(cityAreaCode))
    }
  })
}

export default {
  /**
   * 路网事件类型
   *
   * @param value  0高速  1公路 2全路网
   *
   */
  getCityAreaCode: code => {
    cityAreaCode = code
  },

  /**
   * 获取实时路况
   *
   * @return Promise
   */
  getLiveTrafficLine: async () => {
    await getBaseLine()
    let data = []
    return new Promise(resolved => {
      const params = {
        districtid: '32', // 城市编码 32
        road: '',
        roadType: '' // 类型  G 高速   P 公路  A或不传拿全部
      }
      if (roadType.value == 2) {
        params.roadType = 'P'
        data = baseLineData.gl
      } else if (roadType.value == 1) {
        // 高速
        params.roadType = 'G'
        data = baseLineData.gs
      } else {
        data = [...baseLineData.gs, ...baseLineData.gl]
      }
      trafficApi
        .getTrafficSituationList({
          roadType: roadType.value,
          province: '32',
          city: isProvince.value ? null : areaCode.value,
          forecastType: 1
        })
        .then(res => {
          if (res.data && res.data.length) {
            res.data.map(i => {
              data.push({
                name: `${i.road || ''} ${i.describe || ''} ${i.jamTypeName || ''}`,
                path: i.path.map(it => it),
                roadName: i.roadNum,
                config: {
                  lineColor: lineColors[i.jamTypeName],
                  selectColor: lineColors[i.jamTypeName],
                  zIndex: 110
                }
              })
            })
          }
        })
        .catch(e => {
          console.warn('eee', e)
        })
        .finally(() => {
          resolved({ status: 0, data })
        })
    })
  },

  /**
   * 获取摄像头
   *
   * @return Promise
   */
  getCameraPoint: () => {
    return new Promise((resolve, reject) => {
      if (showJJJ) {
        // baseServiceApi
        //   .getJJJCameraList(1, 32)
        //   .then(res => {
        //     if (res.data && res.data.length) {
        //       console.log(res.data)
        //       res.data = filterPointData(res.data, 'cameraId', 'name', 'lon', 'lat')
        //       resolve({ status: 0, data: res.data })
        //     } else reject({ status: null })
        //   })
        //   .catch(() => {
        //     reject({ status: null })
        //   })
        const data = filterPointData(temporaryFile.videoList, 'cameraId', 'name', 'lon', 'lat')
        resolve({ status: 0, data })
      } else {
        baseServiceApi
          .getCameraList({
            roadType: roadType.value,
            province: 32,
            city: isProvince.value ? '' : areaCode.value,
            orgId: orgId.value,
            status: '1,2', // 1在线 2离线异常,
            companyType: get(store.state, 'user.bussinessType')
          })
          .then(res => {
            if (res.data && res.data.length) {
              resolve({ status: 0, data: filterPointData(res.data, 'cameraId', 'cameraName', 'lon', 'lat') })
            } else resolve({ status: 0, data: null })
          })
          .catch(() => {
            reject({ status: null })
          })
      }
    })
  },

  /**
   * 获取情报板
   *
   * @return Promise
   */
  getIntelligenceBoard: () => {
    return new Promise((resolve, reject) => {
      if (showJJJ) {
        // baseServiceApi
        //   .getIntelligenceBoard()
        //   .then(res => {
        //     if (res.data && res.data.length) {
        //       res.data = res.data.filter(item => item.type == 1)
        //       console.log(res.data)
        //       res.data = filterPointData(res.data, 'id', 'name', 'lon', 'lat')
        //       resolve({ status: 0, data: res.data })
        //     } else reject({ status: null })
        //   })
        //   .catch(() => {
        //     reject({ status: null })
        //   })
        const data = filterPointData(temporaryFile.boardList, 'id', 'name', 'lon', 'lat')
        resolve({ status: 0, data })
      } else {
        baseServiceApi
          .getQbbList({
            roadType: roadType.value,
            province: 32,
            city: isProvince.value ? null : areaCode.value,
            orgId: orgId.value,
            // timeType: '5',
            status: '1,2,3',
            companyType: get(store.state, 'user.bussinessType')

            // status: '0,2' // 高速 0在线 2 异常离线
          })
          .then(res => {
            if (res.data && res.data.length) {
              resolve({ status: 0, data: filterPointData(res.data, 'vmsId', 'vmsName', 'lon', 'lat') })
            } else resolve({ status: 0, data: null })
          })
          .catch(() => {
            reject({ status: null })
          })
      }
    })
  },

  /**
   * 获取交调点
   *
   * @return Promise
   */
  getHandPoint: () => {
    return new Promise((resolve, reject) => {
      baseServiceApi
        .getJddList({
          roadType: roadType.value,
          province: 32,
          orgId: orgId.value,
          city: isProvince.value ? '' : areaCode.value
        })
        .then(res => {
          if (res.data && res.data.length) {
            const result = (res.data || []).map(i => ({
              ...i,
              name: i.gczmc,
              path: [i.lon, i.lat]
            }))
            resolve({ status: 0, data: result })
          } else resolve({ status: 0, data: null })
        })
        .catch(() => {
          reject({ status: null })
        })
    })
  },

  /**
   * 获取应急基地
   *
   * @return Promise
   */
  getEmergencyBase: () => {
    return new Promise((resolve, reject) => {
      baseServiceApi
        .getEmergencyBase({
          orgId: orgId.value
        })
        .then(res => {
          if (res.data && res.data.length) {
            resolve({ status: 0, data: filterPointData(res.data, 'eid', 'ename', 'lon', 'lat') })
          } else resolve({ status: 0, data: null })
        })
        .catch(() => {
          reject({ status: null })
        })
    })
  },

  /**
   * 获取疫情防控
   *
   * @return Promise
   */
  getEpidemic: () => {
    return new Promise((resolve, reject) => {
      const params = {
        province: 32, // string 省份标识
        city: '', // string 城市标识
        roadType: roadType.value, // integer 路网类型（0:公路;1:高速;2:全路网）
        page: 1, // integer 页码
        limit: 1000 //
      }
      baseServiceApi
        .getEpidemic(params)
        .then(res => {
          if (res.data && res.data.list && res.data.list.length) {
            resolve({
              status: 0,
              data: filterPointData(res.data.list, 'epidemicId', 'epidemicName', 'lon', 'lat')
            })
          } else resolve({ status: 0, data: null })
        })
        .catch(() => {
          reject({ status: null })
        })
    })
  },

  /**
   * 获取道路事件点位
   * @return Promise
   */
  getHighSpeed: () => {
    return new Promise((resolve, reject) => {
      const p1 = eventApi.getEventList({ userId: store.state.user.userInfo.userId }) // 高速事件列表
      const dkParams = {
        indRoadCenterId: '4d20bfcc06d94eedbe91eeb5f0d6686f', // 路段中心的ID
        indCenterType: '2', // 路段中心的级别
        province: '32', // 省
        indUnitId: 'qs00001' // 单位ID
      }
      const p2 = eventApi.getAllCoordinate(dkParams) // 获取所有的道口管制事件
      const promiseAllList = [p1, p2]
      Promise.all(promiseAllList).then((result, index) => {
        const resultList = []
        if (result[0] && result[0].data) {
          // 道路事件
          const sjdata = (result[0].data || []).filter(item => {
            return item.eventType !== 'JGB1'
          })
          sjdata.forEach(item => {
            resultList.push({
              ...item,
              id: item.eventId,
              pointSource: 'map',
              name: item.roadNum,
              path: [item.heatModelList[0].lon, item.heatModelList[0].lat]
            })
          })
        }
        if (result[1] && result[1].data) {
          // 交通管制
          const dkData = result[1].data || []
          dkData.forEach(item => {
            resultList.push({
              ...item,
              id: item.id,
              name: item.tsname,
              path: [item.lon, item.lat],
              pointSource: 'map',
              eventType: 'JGB1',
              icon: 'zhdd-gs-jtgz',
              type: 'dlsj'
            })
          })
        }
        console.log('resultList', resultList)
        resolve({ status: 0, data: resultList })
      })
    }).catch(() => resolve({ status: 0, data: null }))
  },

  /**
   * 获取施工摄像头  暂时存在
   * @return Promise
   */
  getConstructionCamera: () => {
    return new Promise((resolve, reject) => {
      try {
        resolve({
          status: 0,
          data: [
            // {
            //   name: '隧道1',
            //   path: [119.14546006910282, 33.69343867830864],
            //   url: 'https://rtmp01open.ys7.com:9188/v3/openlive/E51414628_1_1.flv?expire=1701679849&id=521368131906580480&t=f3d848fc2c5e543057bda837815fdfa5b898c8b7ed4cc78e1d0a0d81875ee24d&ev=100'
            // },
            {
              name: '隧道2',
              path: [118.82734448, 34.10465353],
              url: 'https://rtmp01open.ys7.com:9188/v3/openlive/E51414631_1_1.flv?expire=1701679878&id=521368252715106304&t=6371c2c554f652b66593d57b40d227109043de32af376301472777aa15d8be8a&ev=100'
            },
            {
              name: 'K820+000(淮安三标)借道出口',
              path: [119.133487, 33.68708],
              url: 'https://rtmp01open.ys7.com:9188/v3/openlive/E77565101_1_1.flv?expire=1701680664&id=521371552625721344&t=1b978fff4b270b19011e11813857379427f9832a3ea1ff76193d844eb772f9ab&ev=100'
            },
            // {
            //   name: '王庄天桥',
            //   path: [119.162578, 33.512795],
            //   url: 'https://rtmp01open.ys7.com:9188/v3/openlive/E67675965_1_1.flv?expire=1701680768&id=521371988141285376&t=7ddede24c0b71d8c385ceab583843253544759b1f357c315530d969ad54ac029&ev=100'
            // },
            {
              name: '京沪高速K849+500转序口',
              path: [119.238597, 33.4481],
              url: 'https://rtmp01open.ys7.com:9188/v3/openlive/E93397191_1_1.flv?expire=1701681413&id=521374692246822912&t=2afefde1e1624fe3b71d7a041ac34fb141db425489113672d071bd7878906dd9&ev=100'
            },
            {
              name: '盐洛144转序口',
              path: [119.254861, 33.441486],
              url: 'https://rtmp01open.ys7.com:9188/v3/openlive/E85584658_1_1.flv?expire=1701681596&id=521375460483932160&t=445ab743a782dc873c3422d428c1d445c4d856cb8a353fce5f4d74b55db661e6&ev=100'
            },
            {
              name: 'YZ23 1号球机',
              path: [119.582248, 32.565987],
              url: 'https://rtmp01open.ys7.com:9188/v3/openlive/F33473710_2_1.flv?expire=1701682122&id=521377665119166464&t=5717344f668926e4447c40f140421b7a9f0b303b620c7c9db08c356fb42d2165&ev=100'
            },
            {
              name: 'YZ23 2号球机',
              path: [119.562734, 32.638299],
              url: 'https://rtmp01open.ys7.com:9188/v3/openlive/F33473710_6_1.flv?expire=1701682144&id=521377759134482432&t=88197fc687356e4e8e267d8d29096d6f57a96d924b51e685186bad64744e92bd&ev=100'
            },
            {
              name: '导改: K966+200',
              path: [119.621407, 32.44248],
              url: 'https://rtmp01open.ys7.com:9188/v3/openlive/F55724788_1_2.flv?expire=1701682158&id=521377816407715840&t=707db552605f792a556dc5abb27a8a1fe8f3866a077e1604366c84ee64a5f8dd&ev=100'
            }
          ]
        })
      } catch (e) {
        reject({ status: null })
      }
    })
  },

  /**
   * 获取桥面监测点位
   *
   * @return Promise
   */
  getBridgePoint: () => {
    return new Promise((resolve, reject) => {
      baseServiceApi
        .getBridgeList({
          unitid: 'f00d57e2d82e42dbbf8125dde1d7e665' // orgId.value,
        })
        .then(res => {
          if (res.data && res.data.length) {
            resolve({ status: 0, data: filterPointData(res.data, 'bridgeid', 'bridgeName', 'lon', 'lat') })
          } else resolve({ status: 0, data: null })
        })
        .catch(() => {
          reject({ status: null })
        })
    })
  },
  /**
   * 获取红绿灯管控点位
   *
   * @return Promise
   */
  getTrafficLightPoint: () => {
    return new Promise((resolve, reject) => {
      baseServiceApi
        .getTrafficLightList({
          unitid: 'f00d57e2d82e42dbbf8125dde1d7e665' // orgId.value,
        })
        .then(res => {
          if (res.data && res.data.length) {
            resolve({ status: 0, data: filterPointData(res.data, 'trafficid', 'trafficName', 'lon', 'lat') })
          } else resolve({ status: 0, data: null })
        })
        .catch(() => {
          reject({ status: null })
        })
    })
  }
}
